using System.Security.Cryptography;
using System.Text;
using System.Xml;

namespace LicenseApp.Producer;

/// <summary>
/// RSA密钥对管理类
/// </summary>
public class KeyManager
{
    // 应用程序路径获取 - 按要求实现
    public static string assemblyFilePath = System.Diagnostics.Process.GetCurrentProcess().MainModule?.FileName ?? "";
    public static string assemblyDirPath = System.IO.Path.GetDirectoryName(assemblyFilePath) ?? "";
    public static string PATH = assemblyDirPath;

    private static readonly string KeysDirectory = System.IO.Path.Combine(PATH, "Keys");

    /// <summary>
    /// 为指定客户生成RSA密钥对
    /// </summary>
    /// <param name="customerName">客户名称</param>
    /// <returns>是否成功生成</returns>
    public static bool GenerateKeyPair(string customerName)
    {
        try
        {
            if (string.IsNullOrWhiteSpace(customerName))
                return false;

            // 创建客户目录
            var customerDir = System.IO.Path.Combine(KeysDirectory, customerName);
            System.IO.Directory.CreateDirectory(customerDir);

            // 生成RSA密钥对
            using var rsa = RSA.Create(2048);
            
            // 保存私钥
            var privateKeyPath = System.IO.Path.Combine(customerDir, "private.xml");
            var privateKeyXml = rsa.ToXmlString(true); // true表示包含私钥
            System.IO.File.WriteAllText(privateKeyPath, privateKeyXml, Encoding.UTF8);

            // 保存公钥
            var publicKeyPath = System.IO.Path.Combine(customerDir, "public.xml");
            var publicKeyXml = rsa.ToXmlString(false); // false表示只包含公钥
            System.IO.File.WriteAllText(publicKeyPath, publicKeyXml, Encoding.UTF8);

            return true;
        }
        catch
        {
            return false;
        }
    }

    /// <summary>
    /// 获取所有客户列表
    /// </summary>
    /// <returns>客户名称列表</returns>
    public static List<string> GetCustomers()
    {
        try
        {
            if (!System.IO.Directory.Exists(KeysDirectory))
                return new List<string>();

            return System.IO.Directory.GetDirectories(KeysDirectory)
                .Select(System.IO.Path.GetFileName)
                .Where(name => !string.IsNullOrEmpty(name))
                .Cast<string>()
                .ToList();
        }
        catch
        {
            return new List<string>();
        }
    }

    /// <summary>
    /// 检查客户是否已存在密钥对
    /// </summary>
    /// <param name="customerName">客户名称</param>
    /// <returns>是否存在</returns>
    public static bool CustomerExists(string customerName)
    {
        if (string.IsNullOrWhiteSpace(customerName))
            return false;

        var customerDir = System.IO.Path.Combine(KeysDirectory, customerName);
        var privateKeyPath = System.IO.Path.Combine(customerDir, "private.xml");
        var publicKeyPath = System.IO.Path.Combine(customerDir, "public.xml");

        return System.IO.File.Exists(privateKeyPath) && System.IO.File.Exists(publicKeyPath);
    }

    /// <summary>
    /// 获取客户的私钥
    /// </summary>
    /// <param name="customerName">客户名称</param>
    /// <returns>私钥XML字符串</returns>
    public static string? GetPrivateKey(string customerName)
    {
        try
        {
            if (string.IsNullOrWhiteSpace(customerName))
                return null;

            var privateKeyPath = System.IO.Path.Combine(KeysDirectory, customerName, "private.xml");
            if (!System.IO.File.Exists(privateKeyPath))
                return null;

            return System.IO.File.ReadAllText(privateKeyPath, Encoding.UTF8);
        }
        catch
        {
            return null;
        }
    }

    /// <summary>
    /// 获取客户的公钥
    /// </summary>
    /// <param name="customerName">客户名称</param>
    /// <returns>公钥XML字符串</returns>
    public static string? GetPublicKey(string customerName)
    {
        try
        {
            if (string.IsNullOrWhiteSpace(customerName))
                return null;

            var publicKeyPath = System.IO.Path.Combine(KeysDirectory, customerName, "public.xml");
            if (!System.IO.File.Exists(publicKeyPath))
                return null;

            return System.IO.File.ReadAllText(publicKeyPath, Encoding.UTF8);
        }
        catch
        {
            return null;
        }
    }

    /// <summary>
    /// 获取客户公钥目录路径（用于分发给客户）
    /// </summary>
    /// <param name="customerName">客户名称</param>
    /// <returns>公钥文件路径</returns>
    public static string? GetPublicKeyPath(string customerName)
    {
        if (string.IsNullOrWhiteSpace(customerName))
            return null;

        var publicKeyPath = System.IO.Path.Combine(KeysDirectory, customerName, "public.xml");
        return System.IO.File.Exists(publicKeyPath) ? publicKeyPath : null;
    }

    /// <summary>
    /// 获取客户授权文件路径
    /// </summary>
    /// <param name="customerName">客户名称</param>
    /// <returns>授权文件路径，如果不存在返回null</returns>
    public static string? GetCustomerLicenseFilePath(string customerName)
    {
        if (string.IsNullOrWhiteSpace(customerName))
            return null;

        var licenseFilePath = System.IO.Path.Combine(KeysDirectory, customerName, "license.txt");
        return System.IO.File.Exists(licenseFilePath) ? licenseFilePath : null;
    }

    /// <summary>
    /// 检查客户是否有授权文件
    /// </summary>
    /// <param name="customerName">客户名称</param>
    /// <returns>是否有授权</returns>
    public static bool HasCustomerLicense(string customerName)
    {
        return GetCustomerLicenseFilePath(customerName) != null;
    }

    /// <summary>
    /// 获取客户当前授权码
    /// </summary>
    /// <param name="customerName">客户名称</param>
    /// <returns>授权码内容，如果不存在返回null</returns>
    public static string? GetCustomerLicenseCode(string customerName)
    {
        try
        {
            var licenseFilePath = GetCustomerLicenseFilePath(customerName);
            if (licenseFilePath == null)
                return null;

            return System.IO.File.ReadAllText(licenseFilePath, Encoding.UTF8);
        }
        catch
        {
            return null;
        }
    }

    /// <summary>
    /// 保存授权码到客户目录
    /// </summary>
    /// <param name="customerName">客户名称</param>
    /// <param name="licenseCode">授权码</param>
    /// <returns>是否保存成功</returns>
    public static bool SaveCustomerLicense(string customerName, string licenseCode)
    {
        try
        {
            if (string.IsNullOrWhiteSpace(customerName) || string.IsNullOrWhiteSpace(licenseCode))
                return false;

            var customerDir = System.IO.Path.Combine(KeysDirectory, customerName);
            if (!System.IO.Directory.Exists(customerDir))
                return false; // 客户目录不存在

            var licenseFilePath = System.IO.Path.Combine(customerDir, "license.txt");
            System.IO.File.WriteAllText(licenseFilePath, licenseCode, Encoding.UTF8);
            return true;
        }
        catch
        {
            return false;
        }
    }

    /// <summary>
    /// 清除客户授权文件
    /// </summary>
    /// <param name="customerName">客户名称</param>
    /// <returns>是否清除成功</returns>
    public static bool ClearCustomerLicense(string customerName)
    {
        try
        {
            var licenseFilePath = GetCustomerLicenseFilePath(customerName);
            if (licenseFilePath == null)
                return true; // 文件不存在，视为成功

            System.IO.File.Delete(licenseFilePath);
            return true;
        }
        catch
        {
            return false;
        }
    }
}
